<template>
  <a-card :bordered="false">
    <!-- table区域-begin -->
    <div>
      <vxe-grid
        :height="curHeight"
        size="mini"
        align="center"
        highlight-hover-row
        stripe
        row-key
        row-id="selectedRowKeys"
        id="id"
        keep-source
        :loading="loading"
        column-min-width="150"
        border
        resizable
        auto-resize
        showOverflow
        showHeaderOverflow
        :pager-config="tablePage"
        ref="xGrid"
        :row-config="{ useKey: true,keyField: 'id',isCurrent:true,isHover:true}"
        :checkbox-config="{
          checkRowKeys:selectedRowKeys,
          trigger: 'row',
          highlight: true,
          reserve: true}"
        @sort-change="sortChange"
        @checkbox-change="checkboxChangeEvent"
        @checkbox-all="checkboxChangeEvent"
        :data="dataSource"
        :columns="columns"
        @page-change="handlePageChange"
      >
        <template v-slot:top>
          <div class="table-operator">
          <a-button @click="handleAdd" type="primary" icon="plus">添加用户</a-button>
          <a-button type="primary" icon="download" @click="handleExportXls('用户信息')">导出</a-button>
          <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
            <a-button type="primary" icon="import">导入</a-button>
          </a-upload>
          <j-third-app-button biz-type="user" :selected-row-keys="selectedRowKeys" syncToApp syncToLocal @sync-finally="onSyncFinally"/>
          <a-button type="primary" icon="hdd" @click="recycleBinVisible=true">回收站</a-button>
          <j-super-query :fieldList="superQueryFieldList" @handleSuperQuery="handleSuperQuery"/>
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay" @click="handleMenuClick">
              <a-menu-item key="1">
                <a-icon type="delete"/>
                删除
              </a-menu-item>
              <a-menu-item key="2">
                <a-icon type="lock"/>
                冻结
              </a-menu-item>
              <a-menu-item key="3">
                <a-icon type="unlock"/>
                解冻
              </a-menu-item>
            </a-menu>
            <a-button type="primary" icon="down">批量操作</a-button>
          </a-dropdown>
          </div>
        </template>
        <template v-slot:operate="{ row }">
          <a-button type="primary" shape="circle" @click="handleEdit(row)" icon="edit"/>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a-button type="primary" shape="circle" class="ant-dropdown-link" icon="setting"/>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:;" @click="handleDetail(row)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" @click="handleChangePassword(row.username)">密码</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" @click="handleDelete(row.id)">删除</a>
              </a-menu-item>
              <a-menu-item v-if="row.status==1">
                <a-popconfirm title="确定冻结吗?" @confirm="() => handleFrozen(row.id,2,row.username)">
                  <a>冻结</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item v-if="row.status==2">
                <a-popconfirm title="确定解冻吗?" @confirm="() => handleFrozen(row.id,1,row.username)">
                  <a>解冻</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" @click="handleAgentSettings(row.username)">代理人</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
        <template v-slot:avatarRender="{ row }">
          <div class="anty-img-wrap">
            <a-avatar shape="circle" :src="getAvatarView(row.avatar)" icon="user"/>
          </div>
        </template>
        <template v-slot:statusRender="{ row }" >
          <a-switch :checked="row.status == 1" checked-children="正常" un-checked-children="冻结"  @change="handleFrozen(row)"></a-switch>
        </template>
        <template v-slot:empty>
          <a-empty/>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->
    <user-modal ref="modalForm" @ok="modalFormOk"></user-modal>
    <password-modal ref="passwordmodal" @ok="passwordModalOk"></password-modal>
    <sys-user-agent-modal ref="sysUserAgentModal"></sys-user-agent-modal>
    <!-- 用户回收站 -->
    <user-recycle-bin-modal :visible.sync="recycleBinVisible" @ok="modalFormOk"/>
  </a-card>
</template>

<script>
import UserModal from './modules/UserModal'
import PasswordModal from './modules/PasswordModal'
import {putAction, getFileAccessHttpUrl} from '@/api/manage';
import {frozenBatch} from '@/api/api'
import SysUserAgentModal from "./modules/SysUserAgentModal";
import JInput from '@/components/jeecg/JInput'
import UserRecycleBinModal from './modules/UserRecycleBinModal'
import JSuperQuery from '@/components/jeecg/JSuperQuery'
import JThirdAppButton from '@/components/jeecgbiz/thirdApp/JThirdAppButton'
import {HYListMixin} from "@/mixins/HYListMixin";

export default {
  name: "UserList",
  mixins: [HYListMixin],
  components: {
    JThirdAppButton,
    SysUserAgentModal,
    UserModal,
    PasswordModal,
    JInput,
    UserRecycleBinModal,
    JSuperQuery
  },
  data() {
    return {
      description: '用户管理页面',
      recycleBinVisible: false,
      columns: [
        {type: "checkbox", width: 50, align: "center"},//多选
        {type: "seq", width: 50, align: "center"},//
        {title: '用户账号', align: "center", field: 'username', remoteSort: true},
        {title: '用户姓名', align: "center", field: 'realname',},
        {title: '头像', align: "center", field: 'avatar', slots: {default: 'avatarRender'}},
        {title: '性别', align: "center", field: 'sex_dictText', remoteSort: true},
        {title: '生日', align: "center", field: 'birthday'},
        {title: '手机号码', align: "center", field: 'phone'},
        {title: '组织', align: "center", field: 'departIds_dictText'},
        {title: '状态', align: "center", field: 'status_dictText',slots: {default: 'statusRender'}},
        {title: '操作', fixed: 'right', width: 105, slots: {default: 'operate'}}
      ],
      superQueryFieldList: [
        {type: 'input', value: 'username', text: '用户账号'},
        {type: 'input', value: 'realname', text: '用户姓名'},
        {type: 'select', value: 'sex', dbType: 'int', text: '性别', dictCode: 'sex'},
      ],
      url: {
        syncUser: "/act/process/extActProcess/doSyncUser",
        list: "/sys/user/list",
        delete: "/sys/user/delete",
        deleteBatch: "/sys/user/deleteBatch",
        exportXlsUrl: "/sys/user/exportXls",
        importExcelUrl: "sys/user/importExcel",
      },
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  methods: {
    getAvatarView: function (avatar) {
      return getFileAccessHttpUrl(avatar)
    },
    batchFrozen: function (status) {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return false;
      } else {
        let ids = "";
        let that = this;
        let isAdmin = false;
        that.selectionRows.forEach(function (row) {
          if (row.username == 'admin') {
            isAdmin = true;
          }
        });
        if (isAdmin) {
          that.$message.warning('管理员账号不允许此操作,请重新选择！');
          return;
        }
        that.selectedRowKeys.forEach(function (val) {
          ids += val + ",";
        });
        that.$confirm({
          title: "确认操作",
          content: "是否" + (status == 1 ? "解冻" : "冻结") + "选中账号?",
          onOk: function () {
            frozenBatch({ids: ids, status: status}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        });
      }
    },
    handleMenuClick(e) {
      if (e.key == 1) {
        this.batchDel();
      } else if (e.key == 2) {
        this.batchFrozen(2);
      } else if (e.key == 3) {
        this.batchFrozen(1);
      }
    },
    handleFrozen(row){
      let that = this;
      //TODO 后台校验管理员角色
      if ('admin' == row.username) {
        that.$message.warning('管理员账号不允许此操作！');
        return;
      }
      frozenBatch({ids: row.id, status: row.status == 1?2:1}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.modalFormOk();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    handleChangePassword(username) {
      this.$refs.passwordmodal.show(username);
    },
    handleAgentSettings(username) {
      this.$refs.sysUserAgentModal.agentSettings(username);
      this.$refs.sysUserAgentModal.title = "用户代理人设置";
    },
    passwordModalOk() {
      //TODO 密码修改完成 不需要刷新页面，可以把datasource中的数据更新一下
    },
    onSyncFinally({isToLocal}) {
      // 同步到本地时刷新下数据
      if (isToLocal) {
        this.loadData()
      }
    },
  }
}
</script>
